package com.ship.dispatch.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ship.common.core.exception.BusException;
import com.ship.common.core.web.domain.BaseResultCode;
import com.ship.common.core.web.domain.JsonResult;
import com.ship.common.business.service.impl.BaseServiceImpl;
import com.ship.common.core.utils.BeanCopyUtils;
import com.ship.common.security.utils.SecurityUtils;
import com.ship.dispatch.bean.SmShipCrew;
import com.ship.dispatch.bean.SmShipCrewDetail;
import com.ship.dispatch.bean.SmShipCrewDetailChange;
import com.ship.dispatch.bean.SmShipCrewRecord;
import com.ship.dispatch.bean.treaShipNetwork.IhsShipBase;
import com.ship.dispatch.mapper.SpInformationListMapper;
import com.ship.dispatch.service.SmShipCrewDetailChangeService;
import com.ship.dispatch.service.SmShipCrewDetailService;
import com.ship.dispatch.mapper.SmShipCrewDetailMapper;
import com.ship.dispatch.service.SmShipCrewRecordService;
import com.ship.dispatch.service.SmShipCrewService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
* @author zhangyh
* @description 针对表【sm_ship_crew_detail(船舶船员信息明细表)】的数据库操作Service实现
* @createDate 2024-01-16 16:11:50
*/
@Service
public class SmShipCrewDetailServiceImpl extends BaseServiceImpl<SmShipCrewDetailMapper, SmShipCrewDetail>
    implements SmShipCrewDetailService{

    @Autowired
    private SmShipCrewRecordService smShipCrewRecordService;

    @Autowired
    @Lazy
    private SmShipCrewService smShipCrewService;

    @Autowired
    private SmShipCrewDetailChangeService smShipCrewDetailChangeService;

    @Autowired
    private SpInformationListMapper informationListMapper;

    @Override
    public JsonResult detailAdd(SmShipCrewDetail smShipCrewDetail) {
        if(StringUtils.isBlank(smShipCrewDetail.getMessagePoint())){
            return JsonResult.failed("信息填写节点不能为空");
        }
        if(smShipCrewDetail.getShipCrewId() == null){
            return JsonResult.failed("主信息ID不能为空");
        }
        if(StringUtils.equals("3",smShipCrewDetail.getMessagePoint())){
            smShipCrewDetail.setMessagePoint("4");
        }

        if(StringUtils.equals("4",smShipCrewDetail.getMessagePoint())){
            smShipCrewDetail.setIsTemp("0");
        }else{
            smShipCrewDetail.setIsTemp("1");
        }
        SmShipCrewDetail finalDetail = null;
        if(smShipCrewDetail.getId() != null){
            SmShipCrewDetail old = this.baseMapper.selectById(smShipCrewDetail.getId());
            if(old == null){
                return JsonResult.failed("船员缓存信息异常");
            }
            BeanCopyUtils.copy(smShipCrewDetail,old);
            if(checkPassPortNo(old.getPassportNo())){
                return JsonResult.failed("船员证号已存在");
            }
            this.baseMapper.updateById(old);
            finalDetail = this.baseMapper.selectById(old.getId());
        }else{
            //查询当前用户是否有未完成的缓存数据
            SmShipCrewDetail tempCrewDetail = this.baseMapper.selectOne(
                    new LambdaQueryWrapper<SmShipCrewDetail>()
                            .eq(SmShipCrewDetail::getShipCrewId,smShipCrewDetail.getShipCrewId())
                            .eq(SmShipCrewDetail::getIsTemp,"1")
                            .eq(SmShipCrewDetail::getCreateBy, SecurityUtils.getUsername())
            );
            if(checkPassPortNo(smShipCrewDetail.getPassportNo())){
                return JsonResult.failed("船员证号已存在");
            }
            if(tempCrewDetail != null){
                smShipCrewDetail.setId(tempCrewDetail.getId());
                this.update(smShipCrewDetail
                        ,new LambdaQueryWrapper<SmShipCrewDetail>().eq(SmShipCrewDetail::getId,tempCrewDetail.getId()));
                finalDetail = this.baseMapper.selectById(tempCrewDetail.getId());
            }else{
                this.baseMapper.insert(smShipCrewDetail);
                finalDetail = smShipCrewDetail;
            }

        }
        if(StringUtils.equals("4",finalDetail.getMessagePoint())){
            //增加操作记录
            SmShipCrewRecord crewRecord = new SmShipCrewRecord();
            crewRecord.setShipCrewId(finalDetail.getShipCrewId());
            crewRecord.setOperateType("2");
            crewRecord.setOperateRemark("船员【"+finalDetail.getCrewName()+"】新增");
            crewRecord.setOperateTime(new Date());
            crewRecord.setOperateBy(SecurityUtils.getUsername());
            smShipCrewRecordService.getBaseMapper().insert(crewRecord);

            //更新操作时间
            SmShipCrew smShipCrew = smShipCrewService.getBaseMapper().selectById(finalDetail.getShipCrewId());
            if(smShipCrew != null){
                smShipCrew.setUpdatedBy(SecurityUtils.getUsername());
                smShipCrew.setUpdatedTime(new Date());
                if(StringUtils.isNotBlank(finalDetail.getCrewRank())
                        && StringUtils.equals("Master",finalDetail.getCrewRank()) && StringUtils.equals("1",finalDetail.getStatus())){
                    //更换船长
                    smShipCrew.setMasterName(smShipCrewDetail.getCrewName());

                    //原来的船长状态改为离船
                    List<SmShipCrewDetail> crewDetailList = this.baseMapper.selectList(new LambdaUpdateWrapper<SmShipCrewDetail>()
                            .eq(SmShipCrewDetail::getShipCrewId,smShipCrewDetail.getShipCrewId())
                            .eq(SmShipCrewDetail::getCrewRank,"Master")
                            .eq(SmShipCrewDetail::getStatus,"1")
                    );
                    for (SmShipCrewDetail crewDetail : crewDetailList) {
                        if(StringUtils.equals(crewDetail.getPassportNo(),finalDetail.getPassportNo())){
                            continue;
                        }
                        crewDetail.setStatus("0");
                        this.baseMapper.updateById(crewDetail);
                        updateCrewLoadRecord(crewDetail);
                    }
                }
                //添加船旗国和呼号
                String imo = smShipCrew.getImo();
                if(StringUtils.isNotBlank(imo)){
                    IhsShipBase shipBase = informationListMapper.getShipInfoByImo(imo);
                    if(null != shipBase){
                        smShipCrew.setCallSign(shipBase.getCallsign());
                        smShipCrew.setFlagState(shipBase.getFlagName());
                    }
                }
                smShipCrewService.getBaseMapper().updateById(smShipCrew);
                smShipCrewService.resetCrewCountInfo(smShipCrew);
            }
            updateCrewLoadRecord(finalDetail);
        }
        return JsonResult.success();
    }

    /**
     * 校验船员证唯一
     * @param passportNo
     * @return
     */
    public Boolean checkPassPortNo(String passportNo){
        if(StringUtils.isBlank(passportNo)){
            return false;
        }
        Long count = this.baseMapper.selectCount(
                new LambdaQueryWrapper<SmShipCrewDetail>()
                        .eq(SmShipCrewDetail::getPassportNo,passportNo)
                        .eq(SmShipCrewDetail::getIsTemp,"0")
        );
        return count > 0 ? true : false;
    }

    /**
     * 更新船员上下船状态
     * @param detail
     */
    public void updateCrewLoadRecord(SmShipCrewDetail detail){
        SmShipCrewDetailChange detailChange = new SmShipCrewDetailChange();
        detailChange.setShipCrewId(detail.getShipCrewId());
        detailChange.setCrewName(detail.getCrewName());
        detailChange.setCrewRank(detail.getCrewRank());
        detailChange.setStatus(detail.getStatus());
        detailChange.setUpdatedTime(new Date());
        detailChange.setUpdatedBy(SecurityUtils.getUsername());
        detailChange.setBoatDate(detail.getOnBoatDate() != null ? detail.getOnBoatDate() : new Date());
        detailChange.setBoatPlace(detail.getOnBoatPlace());
        if(StringUtils.equals("0",detailChange.getStatus())){
            detailChange.setBoatDate(detail.getOffBoatDate() != null ? detail.getOffBoatDate() : new Date());
            detailChange.setBoatPlace(detail.getOffBoatPlace());
        }
        smShipCrewDetailChangeService.getBaseMapper().insert(detailChange);
    }
}




